package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.service.TimeLineService;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.util.CollectionUtils;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    //查询个人动态
    @Override
    public PageResult findByuserId(Long userId, Integer page, Integer pagesize) {
        //创建Criteria
        Criteria userId1 = Criteria.where("userId").is(userId);
        //创建query对象
        Query query = Query.query(userId1);
        //查总记录数
        long count = mongoTemplate.count(query, Movement.class);
        //设置分页查询参数
        query.skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //查询分页数据列表
        List<Movement> movements = mongoTemplate.find(query, Movement.class);

        return new PageResult(page, pagesize, count, movements);
    }

    //发布动态
    @Override
    public void publish(Movement movement) {
        //1.保存动态详情
        //1.1设置PID
        movement.setPid(idWorker.getNextId("movement"));
        //1.2设置时间
        movement.setCreated(System.currentTimeMillis());
        //保存数据
        mongoTemplate.save(movement);

        //2.保存好友时间线数据
        timeLineService.saveTimeLine(movement.getUserId(),
                movement.getId());
    }

    /**
     * 查询好友的动态
     *
     * @param page
     * @param pagesize
     * @param friendId 目的:查询该用户id可见的朋友圈
     *                 当前登录用户的id=friendId(发布动态的朋友id且可见),
     *                 1.通过friendId查询中间表得到动态的Id
     *                 2.再通过动态id查询动态表得到动态内容
     * @return
     */
    @Override
    public List<Movement> findFriendMovements(Integer page, Integer pagesize, Long friendId) {
        //1.根据当前用户id查询时间线
        Query query = Query.query(Criteria.where("friendId").is(friendId))
                .skip((page - 1) * pagesize).
                        limit(pagesize).
                        with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> lines = mongoTemplate.find(query, MovementTimeLine.class);
        //2.提取动态id列表
        List<ObjectId> list = CollUtil.getFieldValues(lines, "movementId", ObjectId.class);
        //3.根据动态id查询动态详情,id在list范围,并且状态为 1(审核通过)
        Query movementQuery = Query.query(Criteria.where("id").in(list).and("state").is(1));
        return mongoTemplate.find(movementQuery, Movement.class);
    }

    //随机获取多条动态数据
    @Override
    public List<Movement> randomMovements(Integer counts) {
        //1.创建统计对象,设置统计参数
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(counts));
        //2.调用mongoTemplate方法统计
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //3.获取统计对象
        return results.getMappedResults();
    }

    //根据pid数组查询动态
    @Override
    public List<Movement> findMovementsByPids(List<Long> pids) {
        Query query = Query.query(Criteria.where("pid").in(pids));
        return mongoTemplate.find(query, Movement.class);
    }

    //根据动态id查询动态
    @Override
    public Movement findById(String movementId) {
        //Query query = Query.query(Criteria.where("id").is(movementId));
        Movement movement = mongoTemplate.findById(movementId, Movement.class);
        return movement;
    }

    //根据id查询动态列表
    @Override
    public PageResult findByUserIdList(Integer page, Integer pagesize, Long uid, Integer state) {
        //1.查询数量
        Query query = new Query();
        if (uid != null) {
            query = Query.query(Criteria.where("userId").is(uid));
        }
        //数量
        long count = mongoTemplate.count(query, Movement.class);

        if (state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        //2.查询page的动态
        query.limit(pagesize).skip((page - 1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> list = mongoTemplate.find(query, Movement.class);

        //构造返回值
        return new PageResult(page, pagesize, count, list);
    }

    @Override
    public void update(String movementId, Integer state) {
        Query query = Query.query(Criteria.where("id").in(new ObjectId(movementId)));
        Update update = Update.update("state", state);
        mongoTemplate.updateFirst(query, update, Movement.class);
    }
}
